__version__ = '0.0.7';

'use strict';

let connectButton,disconnectButton;
startup()

function startup() {
    $('#connectButton').click(connect);
    $('#disconnectButton').click(disconnectPeers);
}

let core_pc;
function connect(event) {
        const onopen = (e) => {
        $('#connectButton').attr("disabled",true);
        $('#disconnectButton').attr("disabled",false);
        create_message();
    };
    const onclose = (e) => {
        $('#connectButton').attr("disabled",false);
        $('#disconnectButton').attr("disabled",true);
    };
    const onMessage = onData;

    core_pc = new data_pc(onMessage,onopen,onclose,id = 'core_pc', exchange_method = 'debug', roll = 'sender_adaptive', show_state = true);
}

function disconnectPeers() {
    // Close the RTCPeerConnections
    core_pc.close();
    core_pc = null;
}

function sendData(data) {
    console.log(`sendData:${JSON.stringify(data)}`)
    core_pc.Channel.send(data);
}

let DataRecivers = {

}
function onData(event) {

    for (name in DataRecivers){
        DataRecivers[name](event.data);
    }
        
}

function create_message() {
    append_html(`
    <button id="openMessage" >openMessage</button>
    <button id="closeMessage" disabled>closeMessage</button>
    `);
    $('#openMessage').click(() => {
        function onopen(e){
            $('#message').attr("disabled",false);
            $('#message').focus();
            $('#sendButton').attr("disabled",false);
            $('#openMessage').attr("disabled",true);
            $('#closeMessage').attr("disabled",false);

        };
        function onclose(e){
            $('#message').val("")
            $('#message').attr("disabled",true);
            $('#sendButton').attr("disabled",true);
            $('#openMessage').attr("disabled",false);
            $('#closeMessage').attr("disabled",true);
        };

        function onMessage(event) {
            $('#receivebox').append($("<p></p>").text(event.data))
        }

        _diy_exchange_methods = {
            'init':(self) => {
                DataRecivers['message_pc'] = (data) => {
                    const Data = JSON.parse(data);
                    if (Data.id == 'message_pc'){
                        switch(Data.type){
                            case 'candidates':
                                log("接收到远程candidates！",'important');
                                self._recive_candis(Data.content);
                                break;
                            case 'description':
                                log("接收到远程description！",'important');
                                self._recive_desc(Data.content);
                        }
                    }
                }
            },
            'set':(self) => {
                self.pc.addEventListener("connectionstatechange",(e) => {
                    if (e.target.connectionState === "connected") {
                        log("停止循环发送self_candidates&offer&answer(连接成功)",'important');
                        clearInterval(self.TimeIntervals.candi);
                        log(`线程${self.TimeIntervals.candi}(candi)已经关闭`,'alert');
                        self.TimeIntervals.candi = null;
                        clearInterval(self.TimeIntervals.desc.offer);
                        log(`线程${self.TimeIntervals.desc.offer}已经关闭`,'alert');
                        self.TimeIntervals.desc.offer = null;
                        clearInterval(self.TimeIntervals.desc.answer);
                        log(`线程${self.TimeIntervals.desc.answer}(answer)已经关闭`,'alert');
                        self.TimeIntervals.desc.answer = null;
                      }
                });
                self.pc.addEventListener("signalingstatechange", (e) => {
                    switch(e.target.signalingState) {
                      case "have-remote-offer":
                        log(`停止循环发送offer_description！(收到了远程offer)`,'important');
                        clearInterval(self.TimeIntervals.desc.offer);
                        log(`线程${self.TimeIntervals.desc.offer}已经关闭`,'alert');
                        self.TimeIntervals.desc.offer = null;
                        break;
                    case "have-remote-pranswer": //永远不会发生
                        log(`停止循环发送所有description！(收到了远程answer)`,'important');
                        clearInterval(self.TimeIntervals.desc.offer);
                        log(`线程${self.TimeIntervals.desc.offer}(desc.offer)已经关闭`,'alert');
                        self.TimeIntervals.desc.offer = null;
                        clearInterval(self.TimeIntervals.desc.answer);
                        log(`线程${self.TimeIntervals.desc.answer}(desc.answer)已经关闭`,'alert');
                        self.TimeIntervals.desc.answer = null;
                        break;
                    }
                  });
            },
            'send_desc':(self,localDescription) => {
                const Data = {
                    'id':'message_pc',
                    'type':'description',
                    'content':localDescription
                }
                log(`开始循环发送description！${localDescription.type}`,'important');
                let timeInterval = setInterval(sendData.bind(null,JSON.stringify(Data)),5000)
                log(`线程${timeInterval}(desc.${localDescription.type})已经开启`,'alert');
                if (!self.TimeIntervals){
                    self.TimeIntervals = {
                        'desc':{
                            'offer':null,
                            'answer':null
                        },
                        'candi':null
                    }
                }
                if(self.TimeIntervals.desc[localDescription.type]) clearInterval(self.TimeIntervals.desc[localDescription.type]);
                self.TimeIntervals.desc[localDescription.type] = timeInterval;
                    
            },
            'send_candis':(self,self_candidates) => {
                const Data = {
                    'id':'message_pc',
                    'type':'candidates',
                    'content':self_candidates
                }
                log("开始循环发送self_candidates！",'important');
                let timeInterval = setInterval(sendData.bind(null,JSON.stringify(Data)),5000);
                log(`线程${timeInterval}(candi)已经开启`,'alert');
                if (!self.TimeIntervals){
                    self.TimeIntervals = {
                        'desc':{
                            'offer':null,
                            'answer':null
                        },
                        'candi':null
                    }
                }
                
                if (self.TimeIntervals.candi) clearInterval(self.TimeIntervals.candi);
                self.TimeIntervals.candi = timeInterval;
            },
        }

        let message_pc = new data_pc(onMessage,onopen,onclose,id = 'message_pc', exchange_method = _diy_exchange_methods, roll = 'sender_adaptive', show_state = true);
        
        function sendMessage() {
            let message = $('#message').val();
            message_pc.Channel.send(message);
            $('#message').val('');
            $('#message').focus();
        }

        append_html(`
            <div>
                <label for="message">Enter a message:
                    <input type="text" id="message" placeholder="Message text"
                        inputmode="latin" size=60 maxlength=120 disabled>
                </label>
                <button id="sendButton" disabled>Send</button>
            </div>
            <div id="receivebox">
                <p>Messages received:</p>
            </div>`);

        $('#sendButton').click(sendMessage);



        $('#closeMessage').click((event) => {
            // Close the RTCPeerConnections
            message_pc.close();
            message_pc = null;
        })
    });
}




